const {
	NAME_OR_PASSWORD_IS_REQUIRED,
	NAME_IS_NOT_EXISTS,
	UNAUTHORIZATION,
	NAME_OR_PASSWORD_FAILED
} = require('../config/error')
const userService = require('../service/user.service')
const { md5password } = require('../utils/md5-password')
const { PUBLIC_KEY } = require('../config/secret')
const jwt = require('jsonwebtoken')
const verifyLogin = async (ctx, next) => {
	const { name, password } = ctx.request.body

	// 1.判断用户名和密码是否为空
	if (!name || !password) {
		return ctx.app.emit('error', NAME_OR_PASSWORD_IS_REQUIRED, ctx)
	}

	// 2.查询该用户是否在数据库中存在
	const users = await userService.findUserByName(name)
	const user = users[0]
	console.log(user)
	if (!user) {
		return ctx.app.emit('error', NAME_IS_NOT_EXISTS, ctx)
	}
	// 3.查询密码是否一致
	if (user.password_hash !== md5password(password)) {
		return ctx.app.emit('error', NAME_OR_PASSWORD_FAILED, ctx)
	}

	// 4.将user对象保存到ctx里面
	ctx.user = user
	// 执行下一个中间件
	await next()
}

const verifyAuthorization = async (ctx, next) => {
	// 1.获取token
	const token = ctx.headers.authorization
	console.log(token)
	if (!token) {
		ctx.app.emit('error', UNAUTHORIZATION, ctx)
		return
	}
	// 2.验证token是否有效
	try {
		// 获取token中的信息
		const result = jwt.verify(token, PUBLIC_KEY, {
			algorithms: ['RS256']
		})
		// 保存信息
		ctx.user = result
		console.log(result)
		return await next()
	} catch (err) {
		ctx.app.emit('error', UNAUTHORIZATION, ctx)
	}
}

module.exports = {
	verifyLogin,
	verifyAuthorization
}
